/*
 * koorz公共部分
 * wordall1101@gmail.com
 * 2013-05-14
 * 世界有我更精彩,相信自己,加油!
 */
(function($) { 
	$.koorz = $.koorz || {
        version: "v1.0.0"
    };
    $.extend($.koorz, {
    	util: {
    		uniqueId:function(){
    		    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    		        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    		        return v.toString(16);
    		    });
    		},
    		//判断是否ie6
			isIE6: function() {
				return ($.browser.msie && $.browser.version=="6.0") ? true : false
			},
			trim: function(str) {
				return $.trim(str);
			},
			getStrLength: function(str) {
				str = $.koorz.util.trim(str);
				var theLen = 0,
				strLen = str.replace(/[^\x00-\xff]/g,"**").length;
				theLen = parseInt(strLen/2)==strLen/2 ? strLen/2 : parseInt(strLen/2)+0.5;
				return theLen;
			},
			isEmpty: function(v) {
				return $.koorz.util.trim(v)=="" ? true : false;
			},
	    	submitByEnter : function(e, clk) {
		   		 e = e || window.event;
		   		 var key = e ? (e.charCode || e.keyCode) : 0;
		   		 if(key == 13) {
		   		      clk();
		   		 }
	    	},
	    	getPosition: function(ele){
				var top = ele.offset().top, 
			 	left = ele.offset().left,
				bottom = top + ele.outerHeight(),
				right = left + ele.outerWidth(),
				lmid = left + ele.outerWidth()/2,
				vmid = top + ele.outerHeight()/2;
		
				// iPad position fix
				if (/iPad/i.test(navigator.userAgent)) {
					top -= $(window).scrollTop();
					bottom -= $(window).scrollTop();
					vmid -= $(window).scrollTop();
				}
				var position = {
					leftTop: function(){
						return {x: left, y: top};
					},
					leftMid: function(){
						return {x: left, y: vmid};
					},
					leftBottom: function(){
						return {x: left, y: bottom};
					},
					topMid: function(){
						return {x: lmid, y: top};
					},
					rightTop: function(){
						return {x: right, y: top};
					},
					rightMid: function(){
						return {x: right, y: vmid};
					},
					rightBottom: function(){
						return {x: right, y: bottom};
					},
					midBottom: function(){
						return {x: lmid, y: bottom};
					},
					middle: function(){
						return {x: lmid, y: vmid};
					}
				};			
				return position;
			},
			openWin: function(url){
				var top=100;
				var whichsns = url.substr(url.lastIndexOf("snsType=")+8,1);
				if(whichsns==5){
					var left=document.body.clientWidth>820 ? (document.body.clientWidth-820)/2 : 0;
					window.open(url, 'connect_window', 'height=550, width=800, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}else if(whichsns==1){
					var left=(document.body.clientWidth-580)/2;
					window.open(url, 'connect_window', 'height=620, width=580, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}else if(whichsns==0){//新浪登录框
					var left=document.body.clientWidth>900 ? (document.body.clientWidth-900)/2 : 0;
					window.open(url, 'connect_window', 'height=550, width=900, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}else{
					//renren
					var left=(document.body.clientWidth-580)/2;
					window.open(url, 'connect_window', 'height=420, width=580, toolbar=no, menubar=no, scrollbars=yes, resizable=no,top='+top+',left='+left+', location=no, status=no');
				}
			},
			restrain:function(fn, t){
	    	    var running = false;
	    	    return function(){
	    	        if(running){
	    	        	return;
	    	        }
	    	        running = true;
	    	        fn.apply(null, arguments);
	    	        setTimeout(function(){running = false;}, t);
	    	    };
	    	}
    	}
    });
    $.fn.extend({
    	//快速导航
    	quickNavi: function(){
    		if(!this[0]){
				return;
			}
    		var thiz = $(this);
    		$("#go-up").click(function(){
    			$("html, body").animate({
					scrollTop: 0
				}, 500);
				var topH = $(window).height()+80+"px";
				thiz.data("up",true);
				thiz.css("bottom",topH);
    		});
    		$("#go-down").click(function(){
    			$("html, body").animate({
					scrollTop: $("#wrap").height()
				}, 500);
				thiz.data("up",true);
    		});
			var showEle = function(){
				if(thiz.data("up")){
				}else{
					thiz.css({"opacity":1,"bottom":"200px"});
				}
			};
			$(window).bind("scroll", function(){
				var docScrollTop = $(document).scrollTop();
				(docScrollTop > 0)? showEle(): thiz.css({"opacity":0,"bottom":"-200px"}).data("up",false);
			});
    	},
    	textareaAutoHeight: function(){
    		var obj = this;
    		var h = obj.outerHeight();
			var func = function(){				
				h < 0 && (h = obj.outerHeight());
				if($.browser.mozilla || $.browser.safari){
					obj.height(h);
				}
				var sh = obj[0].scrollHeight,
 				autoHeight = sh < h ? h: sh,
				autoHeight = autoHeight < h * 1.5 ? h: sh;
				obj.height(autoHeight);
			};
			obj.bind("keyup input propertychange focus",func);
    	},
    	textAutoLength: function(options){
    		var settings = {
            	length: 10,
            	tip:"\u8f93\u5165\u5b57\u6570\u8d85\u51fa\u9650\u5236\u8303\u56f4(10)\uff01"
        	};                
        	if(options) {
            	$.extend(settings, options);
        	}
        	
    		var obj = this;
			var func = function(){
				if($.koorz.util.getStrLength(obj.val()) > settings.length){
					$.koorz.tip.show(obj,settings.tip);
				}
			};
			obj.bind("keyup input propertychange focus paste cut keydown blur",func);
    	},
    	wordLimit: function(num){
    		this.each(function(){	
    			if(!num){
    				var copyThis = $(this.cloneNode(true)).hide().css({
    					'position': 'absolute',
    					'width': 'auto',
    					'overflow': 'visible'
    				});
    				$(this).after(copyThis);
    				if(copyThis.width()>$(this).width()){
    					$(this).text($(this).text().substring(0,$(this).text().length-4));
    					$(this).html($(this).html()+'...');
    					copyThis.remove();
    					$(this).wordLimit();
    				}else{
    					copyThis.remove(); //清除复制
    					return;
    				}	
    			}else{
    				var maxwidth=num;
    				if($(this).text().length>maxwidth){
    					$(this).text($(this).text().substring(0,maxwidth));
    					$(this).html($(this).html()+'...');
    				}
    			}					 
    		});
    	},
    	textareaLimit:function(options){
    	    var defaults = {
	            max : 0,
	            callback:function(){}
	        };
	        if(options) {
	            $.extend(defaults, options);
	        };
	        var editor = this;
	        var timer = null ;
	        editor.defaultLength = editor.val().length ;
	        var processChange = function(){
	            var newLength = editor.val().length ;
	            if(defaults.max>0){
	                var num = defaults.max - newLength ;
	                if(num>=0 && num <=10){
	                    defaults.callback(true);
	                    
	                }else if(num<0){
	                    defaults.callback(false);
	                }else{
	                    defaults.callback(true);
	                }
	            }else{
	                
	            }
	            editor.defaultLength = newLength ;
	        };

	        processChange();
	        editor.bind('focus',function(){
	            if(!timer){
	                timer = window.setInterval(function(){
	                    var newLength = editor.val().length ;
	                    if( newLength != editor.defaultLength ){
	                        processChange();
	                    }
	                },10);
	            }
	        });
	        editor.bind('blur', function(){
	            window.clearInterval(timer) ;
	            timer = null;
	        });
	    },
    	dropDown: function(options){
        	var settings = {
            	event: "mouseover",
            	classNm: ".dropdown",
            	active:"active",
            	timer: null,
            	fadeSpeed: 100,
            	duration: 500,
            	offsetX: 82,
            	offsetY: 8,
            	isLocation: false
        	};                
        	if(options) {
            	$.extend(settings, options);
        	}
        	
        	var triggers = this;
            triggers.each(function() {
                $this = $(this);
    			$this.hover(function(){
					clearTimeout(settings.timer);
					var $dropDown = $("."+settings.active);
					$dropDown.removeClass(settings.active);
					$dropDown.fadeOut(settings.fadeSpeed);
					
					$dropDown = $(this).children(settings.classNm);
					$dropDown.addClass(settings.active);
					if(settings.isLocation){
						var position = $.koorz.util.getPosition($(this)).rightBottom();
						$dropDown.css({
							left: position.x - settings.offsetX + "px",
							top: position.y + settings.offsetY + "px"
						});
					}
					$dropDown.fadeIn(settings.fadeSpeed);
				},function(){
					settings.timer = setTimeout(function(){
						var $dropDown = $("."+settings.active);
						$dropDown.removeClass(settings.active);
						$dropDown.fadeOut(settings.fadeSpeed);
					},settings.duration);
				});
			});
    	}
    });
})(jQuery);

/**
 * 加载页面
 */
$.koorz.loadpage = {
	conf: {
		id:"",
		url:"",
		ajaxData:{},
		onBefore:false,
		onComplete:false
	},
	load: function(){
		var loadpage = $.koorz.loadpage;
		if($(loadpage.conf.id)[0]){
			if ($.isFunction(loadpage.conf.onBefore)) { 
				loadpage.conf.onBefore($(loadpage.conf.id));
			}
		   	$.get(loadpage.conf.url,loadpage.conf.ajaxData,function(resp) {
		   		if(resp){
		   			var container = $(loadpage.conf.id);
		   			container.empty();
		   			container.append(resp);
		   			if ($.isFunction(loadpage.conf.onComplete)) { 
		   				loadpage.conf.onComplete(container,resp);
					}
		   		}
		    });
		}
	}
};

/**
 * 获取商品列表
 */
$.koorz.getWaterfall = {
	conf: {
		visitNum:0,
		page:'#pagination',
		tips:'#tips',
		loading:'#loading',
		list:'#goods-wall',
		item:'.good-item',
        ajaxUrl: KOORZ.path + "/api/style",
        ajaxData: {
        	page:1,
        	pageSize:124
        }
    },
    init: function() {
    	var self = $.koorz.getWaterfall,
		conf = self.conf;
    	//瀑布流图片初始化
    	$(conf.list).masonry({
            itemSelector: conf.item,
            isFitWidth:true
        });
		
		$(self.conf.page).pagination({
			maxentries:0,
			prev_show_always:false,
			next_show_always:false,
			num_edge_entries: 1,
			num_display_entries: 4,
			items_per_page:2,
			link_to:"javascript:void(0)",
			prev_text: "上一页",
			next_text: "下一页",
			ajax:{
				on: true,
	            url:conf.ajaxUrl,
	            dataType: 'json',
	            param:function(currentPage,pageSize){
	            	conf.ajaxData.page = currentPage+1;
	            	return conf.ajaxData;
	            },
	            ajaxStart: function(){
	            	$(conf.list).empty();
	            	$(conf.tips).hide();
					$(conf.loading).show();
	            },
	            callback: function(data) {
	            	$(conf.loading).hide();
	            	if(data.list.length == 0){
	            		$(conf.tips).show();
	            	}else {
	            		self.flowGoods(data.list);
	            	}
	            }
			}
		});
    },
    flowGoods: function(list) {
    	var conf = $.koorz.getWaterfall.conf,
		items = "";
        $.each(list,function(key,val) {
        	var detailUrl = "";
        	if(val.type==0){
        		detailUrl = KOORZ.path+'/single/'+val.id;
        	}else {
        		detailUrl = KOORZ.path+'/style/'+val.id;
        	}
        	items += '<div class="good-item">';
        	items += '<div class="pic"  style="height:'+val.waterfall_height+'px;" >';
        	items += '<a  href="'+detailUrl+'" target="_blank"> ';
        	items += '<img width="'+val.waterfall_width+'px;" height="'+val.waterfall_height+'px;"' ;
        	items += 'data-original="'+val.waterfall_url+'"/>';
        	
        	if(val.style_items && val.style_items.length > 0){
        		items += '<span class="icons">';
        		$.each(val.style_items,function(k,v) {
        			if(v.category_id == "100012"){
        				items += '<span class="icon-shangyi"></span>';
 					}else if(v.category_id == "100014"){
 						items += '<span class="icon-waitao"></span>';
 					}else if(v.category_id == "100007"){
 						items += '<span class="icon-ku"></span>';
 					}else if(v.category_id == "100009"){
 						items += '<span class="icon-lianyiqun"></span>';
 					}else if(v.category_id == "100006"){
 						items += '<span class="icon-xie"></span>';
 					}else if(v.category_id == "100013"){
 						items += '<span class="icon-bao"></span>';
 					}else if(v.category_id == "100010"){
 						items += '<span class="icon-peishi"></span>';
 					}
        		});
        		items += '</span>';
        	}
        	
        	items += '</a>';
        	items += '<a href="'+detailUrl+'" class="goods_title_seo">'+val.description+'</a>';
        	items += '</div>';
        	items += '<div class="good-desc-wrap">';
        	items += '<div class="overlay"></div>';
        	
        	if(val.type==0){
        		items += '<div class="price"><span>￥'+val.price+'</span></div>';
        	}
        	
        	items += '<p class="desc">';
        	items += '<a href="'+detailUrl+'" title="'+val.description+'" target="_blank">'+val.description+'</a>';
        	items += '</p>';
        	items += '</div>';
        	items += '</div>';
        });
        var $boxes = $(items);
        var bricks = $(conf.list);
        bricks.append( $boxes ).masonry('appended',$boxes);
        bricks.masonry('reload');
        $('img[data-original]').lazyload({effect:'fadeIn',failure_limit:10});
    }
};

//设置模板菜单事件
$.koorz.templateMenu = {
	init: function() {
    	$(".template-menu .menu-item").click(function(){
    		$(".template-menu").find('.sel').removeClass('sel');
    		$(this).addClass('sel');
    		$.koorz.getTemplate.clear();
    		$.koorz.getTemplate.conf.ajaxUrl = KOORZ.path + $(this).children().attr("href");
    		$.koorz.getTemplate.init();
    		return false;
        });
    }
};

//获取模板数据
$.koorz.getTemplate = {
	conf: {
		distance: 100,
		page: 1,
        ajaxUrl: KOORZ.path + "/api/templet/100052",
        ajaxData: {
        	page:1,
        	pageSize:15
        }
    },
    clear:function(){
    	var self = $.koorz.getTemplate;
    	self.conf.page=1;
    	$(".template-item-list").empty();
    	$(".template-item-list").masonry('destroy');
    	$("#right-toolbar").unbind("scroll", self.lazyLoad);
    },
    init: function() {
    	var self = $.koorz.getTemplate;
    	//瀑布流图片初始化
    	$(".template-item-list").masonry({
            itemSelector:'.template'
            //isFitWidth:true
        });
    	self.ajaxLoad();
		$("#right-toolbar").bind("scroll", self.lazyLoad);
    },
    isLoading: false,
    lazyLoad: function() {
    	var self = $.koorz.getTemplate;
        var distanceToBottom = $(document).height() - $("#right-toolbar").scrollTop() - $("#right-toolbar").height();
        if (!self.isLoading && distanceToBottom < self.conf.distance) {
        	self.ajaxLoad();
        }
    },
    ajaxLoad: function() {
    	var self = $.koorz.getTemplate,
		conf = $.koorz.getTemplate.conf;
    	conf.ajaxData.page = conf.page;
        
        $.ajax({
            url: conf.ajaxUrl,
            type: "get",
            dataType: "json",
            timeout: 70000,
            data: conf.ajaxData,
            error: function(XMLHttpRequest, textStatus, errorThrown){
            	$(".template-content .loading").hide();
            },
            beforeSend:function () {
            	self.isLoading = true;
            	$(".template-content .loading").show();
            },
            complete:function () {
            	self.isLoading = false;
            	$(".template-content .loading").hide();
            },
            success: function(resp) {
            	if(resp.list.length == 0){
            		$("#right-toolbar").unbind("scroll", self.lazyLoad);
            	}else{
            		self.flowGoods(resp.list);
            		conf.page += 1;
            	}
            }
        });
    },
    flowGoods: function(list) {
    	var self = $.koorz.getTemplate;
        var items = "";
        $.each(list,function(key,val) {
        	var rwidth=110;
        	var rheight=val.waterfall_height*rwidth/val.waterfall_width;
        	
        	items += '<div class="template" template-id="'+val.id+'">';
        	items +='<div class="template-image" style="height:'+(rheight+2)+'px;">';
        	items +='<img  wid='+val.waterfall_width+' hei='+val.waterfall_height+' height='+rheight+' data-original="'+val.waterfall_url+'" alt="'+val.description+'">';
        	items +='</div>';
        	items +='<div class="template-title">'+val.description+'</div>';
        	items +="</div>";
        });
        var $boxes = $(items);
        $(".template-item-list").append( $boxes ).masonry('appended',$boxes);
        $(".template-item-list").masonry('reload');
        
        $('img[data-original]').lazyload({effect:'fadeIn',failure_limit:10});
        $(".template").click(function(){
            $('.template.sel').removeClass('sel');
            $(this).addClass('sel');
            var id = $(this).attr('template-id');
            $.koorz.imageBaker.init(id,"http://static.koorz.com/images/"+id+"_normal.jpeg");
        });
    }
};

$.koorz.imageBaker = {
	init:function(id,url){
		$('.default-image').hide();
		$('#image-baker .image-bg').attr("src",url);
		$('#image-baker').attr('template-id',id);
		$('#image-baker').show();
		$('#image-baker .image-view').click(function(){
			if ($.koorz.stepTab.conf.stepIndex == 0) {
                $('#template-container').hide();
                $('#step0').removeClass('sel');
                $('#step1').addClass('sel');
                $.koorz.stepTab.conf.stepIndex = 1;
            }
			if ($('#item-container').attr('type')==$(this).attr('type'))
                return false;
            
            $('#image-baker .image-view.sel').removeClass('sel');
            $(this).addClass('sel');

            $.koorz.getSingles.clear();
            
            $('#item-container').attr('type', $(this).attr('type'))
                .attr('type-name', $(this).attr('type-name'));
            $('#item-container').find(".item-menu a").text("全部"+$(this).attr('type-name'));
            
            $.koorz.getSingles.conf.ajaxUrl = KOORZ.path + $(this).attr("url");
    		$.koorz.getSingles.init();
            
            $('#item-container').show();

            return false;
		});
		submitCheck();
	},
	imageViewSet:function(view, itemId, src){
		$.koorz.imageBaker.imageViewClear(view);
	    $(view).find('.image-view-text').hide();

	    $(view).attr('item-id', itemId).addClass('fill').addClass('sel');

	    var w = $(view).width(), h = $(view).height();
	    var close = $('<span>').addClass('close').click(function(){ $.koorz.imageBaker.imageViewClear(view); return false; });
	    var img = $('<img>')
	        .attr('src', src+'?'+Math.random()).load(function(){
	            // 居中显示
	            var iw = $(img).width(), ih = $(img).height();
	            var r = iw / w > ih / h ? iw / w : ih / h;
	            var rw = iw / r, rh = ih / r;
	            var l = Math.floor((w - rw) / 2), t = Math.floor((h - rh) / 2);
	            $(img).css({ width: rw, height: rh, margin: t+'px 0 0 0' });

	            $(close).css({top: t+'px', right: l+'px'});
	        }).css({ 'max-width': w+'px', 'max-height': h+'px' });
	    $(view).append(img).append(close);
	},
	imageViewClear:function(view){
		if (!view) view = this;
	    if ($(view).attr('item-id')==$('.item.sel').attr('item-id')) {
	        $('.item.sel').removeClass('sel');
	    }
	    $(view).removeClass('fill').attr('item-id', '');
	    $(view).find('img').remove();
	    $(view).find('.close').remove();
	    $(view).find('span').show();
	    submitCheck();
	}
};

/**
 * 发布搭配时检查是否已经选择好
 */
function submitCheck() {
    var empty = true;
    $('#image-baker .image-view').each(function(i,e){
        if ($(e).attr('item-id') > 0) {
            empty = false;
        } 
    });
    if (empty) {
        $('#submit').addClass('disable');
    } else {
        $('#submit').removeClass('disable');
    }
    return !empty;
}

$.koorz.stepTab = {
	conf:{
		stepIndex:0
	},
	init:function(id,url){
		$('#step0 a').click(function(){
			$.koorz.util.restrain(function(){
				var conf = $.koorz.stepTab.conf;
				if(conf.stepIndex == 0){
					return false;
				}
				$.koorz.getSingles.clear();
				$('#step0').addClass('sel');
			    $('#step1').removeClass('sel');
			    $('#item-container').hide();
			    $('#template-container').show();
			    conf.stepIndex = 0;
			    submitCheck();
			},300)();
			return false;
		});
		$('#step1 a').click(function(){
			$.koorz.util.restrain(function(){
				if(!$.koorz.util.isEmpty($('#image-baker').attr('template-id'))){
				    $($('#image-baker .image-view')[0]).click();
				}
			},300)();
			return false;
		});
		submitCheck();
	}
};

//获取模板单品数据
$.koorz.getSingles = {
	conf: {
		distance: 100,
		page: 1,
        ajaxUrl: KOORZ.path + "/style/singles/1",
        ajaxData: {
        	page:1,
        	pageSize:15
        }
    },
    clear:function(){
    	var self = $.koorz.getSingles;
    	self.conf.page=1;
    	$(".item-list").empty();
    	$('#item-container').removeAttr('type-name').removeAttr('type');
    	//$(".item-list").masonry('destroy');
    	$("#right-toolbar").unbind("scroll", self.lazyLoad);
    },
    init: function() {
    	var self = $.koorz.getSingles;
    	//瀑布流图片初始化
    	$(".item-list").masonry({
            itemSelector:'.item'
            //isFitWidth:true
        });
    	self.ajaxLoad();
		$("#right-toolbar").bind("scroll", self.lazyLoad);
    },
    isLoading: false,
    lazyLoad: function() {
    	var self = $.koorz.getSingles;
        var distanceToBottom = $(document).height() - $("#right-toolbar").scrollTop() - $("#right-toolbar").height();
        if (!self.isLoading && distanceToBottom < self.conf.distance) {
        	self.ajaxLoad();
        }
    },
    ajaxLoad: function() {
    	var self = $.koorz.getSingles,
		conf = $.koorz.getSingles.conf;
    	conf.ajaxData.page = conf.page;
        
        $.ajax({
            url: conf.ajaxUrl,
            type: "get",
            dataType: "json",
            timeout: 70000,
            data: conf.ajaxData,
            error: function(XMLHttpRequest, textStatus, errorThrown){
            	$(".item-content .loading").hide();
            },
            beforeSend:function () {
            	self.isLoading = true;
            	$(".item-content .loading").show();
            },
            complete:function () {
            	self.isLoading = false;
            	$(".item-content .loading").hide();
            },
            success: function(resp) {
            	if(resp.list.length == 0){
            		$("#right-toolbar").unbind("scroll", self.lazyLoad);
            	}else{
            		self.flowGoods(resp.list);
            		conf.page += 1;
            	}
            }
        });
    },
    flowGoods: function(list) {
    	var self = $.koorz.getSingles;
        var items = "";
        $.each(list,function(key,val) {
        	items += '<div class="item" item-id="'+val.id+'">';
        	items +='<div class="item-image">';
        	items +='<img  data-original="'+val.waterfall_url+'" alt="'+val.description+'">';
        	items +='</div>';
        	items +="</div>";
        });
        var $boxes = $(items);
        $(".item-list").append( $boxes ).masonry('appended',$boxes);
        $(".item-list").masonry('reload');
        
        $('img[data-original]').lazyload({effect:'fadeIn',failure_limit:10});
        $(".item").click(function(){
        	if ($(this).attr('item-id')==$('.item.sel').attr('item-id'))
                return false;
            
            $('.item.sel').removeClass('sel');
            $(this).addClass('sel');
            
            var view = $('.image-view[type='+$('#item-container').attr('type')+']');
            $.koorz.imageBaker.imageViewSet(view, $(this).attr('item-id'), $(this).find('img').attr('src'));
            submitCheck();
        });
    }
};

/**
 * 发布搭配
 */
$.koorz.styleUpload = {
		conf:{
			stepIndex:0
		},
		init:function(id,url){
			$("#submit").click(function(){
				$.koorz.styleUpload.submit();
			});
			$("#words").textareaLimit({max:200, callback:
				function(s){
					if(!s){
						var editor = $("#words");
						editor.val(editor.val().substring(0,200));
						alert("200个字以内就可以了哦");
					}
				}
			});
		},
		submit:function(){
			if (!submitCheck()) {
		        return false;
		    }
		    if (!$.koorz.login.isLogin()) return false;
		    
		    if ($.koorz.util.isEmpty($('#words').val())) {
		        $('#words').focus();
		        return false;
		    }

		    var view_items = "[";
		    var empty_view = false;
		    $('.image-view').each(function(index){
		        if (!$(this).attr('item-id')) {
		            empty_view = true;
		            return;
		        }
		        var item_img = $($(this).find("img").first()),
		        top = $(this).position().top,
		        left = $(this).position().left;;
		        view_items = view_items + '{"item_id":"'+$(this).attr('item-id')+'",'+
		        '"width":"'+item_img.width()+'","height":"'+item_img.height()+'","top":"'+top+'","left":"'+left+'"},';
		    });
		    view_items = view_items.substring(0,view_items.length-1);
		    view_items = view_items + "]";
		    if (empty_view) {
		        alert('请先完成搭配');
		        return;
		    }
		    var da = {
		    	koorz_form_token:$("input[name='koorz_form_token']").val(),
		        content : $('#words').val(),
		        template_id : $('#image-baker').attr('template-id'),
		        view_items : view_items,
		        _ : new Date().getTime()
		    };
		    $.ajax({
	            url: KOORZ.path +"/style/publish",
	            type: "post",
	            dataType: "json",
	            data: da,
	            error: function(XMLHttpRequest, textStatus, errorThrown){
	            	alert("提交出错，请重试。");
	            },
	            success: function(resp) {
	            	if(resp.code == "100"){
	            		alert(resp.msg);
	            	}else {
	            		location = '/style/' + resp.data;
	            	}
	            }
	        });
		}
};

//获取需要分页的列表数据，对结果数据的操作由调用者自己处理；
$.koorz.getList = {
	conf:{
		page:'#pagination',
		tips:'#tips',
		loading:'#loading',
		list:'#list',
		url:"",
		callback:false
	},
	data:{
		page:1,
		pageSize:10
	},
	init:function(){
		var self = $.koorz.getList;
		if($.koorz.util.isEmpty(self.conf.url))return false;
		$(self.conf.page).pagination({
			maxentries:0,
			prev_show_always:false,
			next_show_always:false,
			num_edge_entries: 1,
			num_display_entries: 4,
			items_per_page:2,
			prev_text: "上一页",
			next_text: "下一页",
			ajax:{
				on: true,
	            url:KOORZ.path+self.conf.url,
	            dataType: 'json',
	            param:function(currentPage,pageSize){
	            	var data = self.data;
	            	data.page = currentPage+1;
	            	return data;
	            },
	            ajaxStart: function(){
	            	$(self.conf.list).empty();
	            	$(self.conf.tips).hide();
					$(self.conf.loading).show();
	            },
	            callback: function(data) {
	            	$(self.conf.loading).hide();
	            	if(data.list.length == 0){
	            		$(self.conf.tips).show();
	            	}else {
	            		if(self.conf.callback){
	            			self.conf.callback(data.list,$(self.conf.list));
	            		}
	            	}
	            }
			}
		});
	}
};


//授权登录后回调
window.redirect = function(code,site,user){
	if(code == "200"){
		window.location.reload();
	}
};

/**
 * 登录
 */
$.koorz.login = {
	init:function(){
		var self = $.koorz.login;
		if(!self.isLogin()){
			$("#header-wrapper .login").click(function(){
				self.login();
				return false;
			});
		}
	},
	isLogin: function(){
		if($.koorz.util.isEmpty(KOORZ.uid))return false;
		return true;
	},
	login: function(){
		var html = "";
		html += '<div class="login-account">';
		html += '<div class="titleBar clearfix"><a class="close" href="javascript:void(0)"></a><span>嗨！欢迎！</span></div>';
		html += '<div class="login-openid">';
		html += '<h4><span></span><em>使用合作网站帐号登录</em></h4>';
		html += '<div class="site-openid clearfix">';
		html += '<ul>';
		html += '<li class="weibo"><a id="weibo_auth" href="'+KOORZ.path+'/user/snsLogin?snsType=0"><i></i><p>新浪微博</p></a></li>';
		html += '<li class="qq"><a href="'+KOORZ.path+'/user/snsLogin?snsType=1"><i></i><p>QQ</p></a></li>';
		html += '<li class="douban"><a href="'+KOORZ.path+'/user/snsLogin?snsType=2"><i></i><p>豆瓣</p></a></li>';
		//html += '<li class="renren"><a href="'+KOORZ.path+'/user/snsLogin?snsType=3"><i></i><p>人人网</p></a></li>';
		html += '<li class="taobao"><a id="taobao_auth" href="'+KOORZ.path+'/user/snsLogin?snsType=5"><i></i><p>淘宝</p></a></li>';
		html += '</ul>';
		html += '</div>';
		html += '</div>';
		html += '</div>';
		
		$.colorbox({html:html,scrolling:false,width:"650",opacity:0.1,speed:500,
			onComplete:function(){
				$(".site-openid a").click(function(){
					if($(this).attr("id") == "weibo_auth" || $(this).attr("id") == "taobao_auth"){
						$.koorz.util.openWin($(this).attr("href"));
					}else {
						alert("稍候开通！");
					}
					return false;
				});
				
				$(".login-account .close").click(function(){
					$.colorbox.close();
					return false;
				});
			},
			onClosed:function(){
				
			}
		});
	}
};

$(function() {
	$(".header-navi li").dropDown({
		classNm: ".drop-down",
    	duration:65
	});
	$(".header-user-info li").dropDown({
		classNm: ".drop-down",
    	duration:65
	});
	$.koorz.login.init();
	$('.quick-navi').quickNavi();
});